var Play = (function(){
	var catItemFun,
		songListFun;
	var my_media;
	function update(){
		var voaData = VoaStorage.getStorage();
		var html = '';
	    html = catItemFun({
	    	title: Conf.title,
	    	cover: Conf.cover,
	    	list: voaData.config.list,
	    	song: voaData.song
	    });
	    $(".content-cat").html(html);
	}

	function getCurPos(isFirst){
		window.my_media = my_media;
		
		if(my_media){
			my_media.getCurrentPosition(
		        // success callback
		        function (position) {
		            if (position > -1) {
		            	if(isFirst){
		            		var dur = my_media.getDuration(),
					    		m = Math.floor(dur/60),
					    		s = Math.ceil(dur%60);
					    	$('.play-duration').html((m<10 ? '0'+m : m) +':'+ (s<10?'0'+s: s));
		            	}
		                var dur = my_media.getDuration();
		                var per = position/dur*100;
		                var m = Math.floor(position/60),
	        				s = Math.ceil(position%60);
	        			$('.play-cur-time').html((m<10 ? '0'+m : m) +':'+ (s<10?'0'+s: s));

		                $('.play-progress-dot').css('left', per+'%');
		                Lyric.move(position);
		                setTimeout(getCurPos, 500);
		            }
		        },
		        // error callback
		        function (e) {
		            console.log("Error getting pos=" + e);
		        }
		    );
			
		}
	}

	function playSong(cat, uid){
		var songData = VoaStorage.getSongByUid(uid, cat);
		console.log(songData);
		if(my_media){
			my_media.stop();
			my_media.release();
		}
		my_media = new Media(
			cordova.file.externalRootDirectory+'51voa/mp3/'+cat+'/'+songData.name+'.mp3',
	        // success callback
	        function () {
	        	console.log('play song done');
	        },
	        // error callback
	        function (err) { console.log("playAudio():Audio Error: " + err); }
	    );

	    // Play audio
	    my_media.play();

    	getCurPos(true);
    	rootDirEntry.getFile('article/'+cat+'/'+songData.name+'.txt', {}, function(fileEntry) {

		    // Get a File object representing the file,
		    // then use FileReader to read its contents.
		    fileEntry.file(function(file) {
				var reader = new FileReader();

				reader.onloadend = function(e) {
					var text = this.result;
					console.log(text);
					text = text.replace(/\n/g,'</p><p>');
					text = '<p>'+text+'</p>';
					$('.play-content-text').html(text);
				};

				reader.readAsText(file);
		    }, function(e){
		    	console.log('trans error 2');
		    	console.log(e);
		    });

		}, function(e){
	    	console.log('trans error 1');
	    	console.log(e);
	    });

    	if(songData.hasLyric){
    		Lyric.play(
		    	'lyric/'+cat+'/'+songData.name+'.lrc'
		    );
    	}else{
    		$('.play-content-lyric').html('<div class="play-no-lyric">没有歌词</div>')
    	}
    	if(songData.hasTranslation){
    		rootDirEntry.getFile('translation/'+cat+'/'+songData.name+'.txt', {}, function(fileEntry) {

			    // Get a File object representing the file,
			    // then use FileReader to read its contents.
			    fileEntry.file(function(file) {
					var reader = new FileReader();

					reader.onloadend = function(e) {
						var text = this.result;
						text = text.replace(/\n/g,'<br>');
						$('.play-content-translation').html(text);
					};

					reader.readAsText(file);
			    }, function(e){
			    	console.log('trans error 2');
			    	console.log(e);
			    });

			}, function(e){
		    	console.log('trans error 1');
		    	console.log(e);
		    });	
    	}
    	
	    $('.play-btn-play').removeClass('play-btn-paused');

	    $('.doc').addClass('play-zone');
	}
	function init(){
		catItemFun = $("#catTpl").html().tmpl();
		songListFun = $('#songListTpl').html().tmpl();
		update();

		$('.content-cat').delegate('.cat-item', 'tap', function(){
			var catItem = $(this),
				cat = catItem.data('cat');
			$('.page-song-list .btn-return').html(Conf.title[cat]);
			var voaData = VoaStorage.getStorage();
			var html = songListFun({
				list: voaData.song[cat],
				cat: cat
			});
			$('.page-song-list .ui-content').html(html);
			$('.doc').addClass('song-list-zone');
		});
		$('.page-song-list .btn-return').tap(function(){
	    	$('.doc').removeClass('song-list-zone');
	    });

		$('.page-song-list .ui-content').delegate('.song-list-item', 'tap', function(){
			var item = $(this);
			playSong(item.data('cat'), item.data('uid'));
		});


		//event for minibar
		$('.mi-song-cover, .mi-song-info').tap(function(){
			$('.doc').addClass('play-zone');
		});

		//event for play control
		$('.play-btn-play').tap(function(){
			var btn = $(this);
			if(btn.hasClass('play-btn-paused')){
				if(my_media){
					my_media.play();
					btn.removeClass('play-btn-paused');
				}
			}else{
				if(my_media){
					my_media.pause();
					btn.addClass('play-btn-paused');
				}
			}
		});

		var contentType = ['playlist', 'cover', 'lyric', 'text', 'translation'],
	        curContentIndex = 0;
	    $('.play-content-box').swipeRight(function(){
	        if(curContentIndex==0) return;
	        
	        var oldType = contentType[curContentIndex];
	        curContentIndex--;
	        var type = contentType[curContentIndex];
	        $('.play-content-box').removeClass('play-content-cur-'+oldType).addClass('play-content-cur-'+type);

	        $('.play-mini-nav-item')
	            .removeClass('play-mini-nav-item-cur')
	            .eq(curContentIndex)
	            .addClass('play-mini-nav-item-cur');
	    });
	    $('.play-content-box').swipeLeft(function(){
	        if(curContentIndex==4) return;
	        
	        var oldType = contentType[curContentIndex];
	        curContentIndex++;
	        var type = contentType[curContentIndex];
	        $('.play-content-box').removeClass('play-content-cur-'+oldType).addClass('play-content-cur-'+type);
	        $('.play-mini-nav-item')
	            .removeClass('play-mini-nav-item-cur')
	            .eq(curContentIndex)
	            .addClass('play-mini-nav-item-cur');
	    });
	    $('.play-collapse').tap(function(){
	        $('.doc').removeClass('play-zone');
	    });
	}
	return{
		init: init
	}
})();